import SwiftUI
import AVFoundation
import UIKit
import Photos // 导入用于保存照片的框架

// 用于管理相机相关逻辑的类，遵循NSObject和AVCapturePhotoCaptureDelegate协议
class PhotoCaptureManager: NSObject, AVCapturePhotoCaptureDelegate {
    var captureSession: AVCaptureSession?
    var previewLayer: AVCaptureVideoPreviewLayer?
    var photoOutput: AVCapturePhotoOutput?
    
    func setupCamera() {
        // 创建会话
        captureSession = AVCaptureSession()
        
        // 获取前置摄像头设备
        guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for:.video, position:.front) else { return }
        print(device)
        
        do {
            // 创建输入设备
            let input = try AVCaptureDeviceInput(device: device)
            if (captureSession?.canAddInput(input))! {
                captureSession?.addInput(input)
            }
        } catch {
            print("Error setting device input: \(error)")
            return
        }
        
        photoOutput = AVCapturePhotoOutput()
        if (captureSession?.canAddOutput(photoOutput!))! {
            captureSession?.addOutput(photoOutput!)
        }
        
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
        previewLayer?.videoGravity = .resizeAspectFill
    }
    
    func startCamera() {
        captureSession?.startRunning()
    }
    
    func takePhoto() {
        // 配置拍照设置
        let settings = AVCapturePhotoSettings()
        print(settings)
        if let photoOutput = photoOutput {
            photoOutput.capturePhoto(with: settings, delegate: self)
            print("photooutput")
        }
    }
    
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let imageData = photo.fileDataRepresentation(), let image = UIImage(data: imageData) {
            // 请求保存图片到相册的权限并保存图片
            print("请求相册权限")
            PHPhotoLibrary.requestAuthorization { status in
                if status == .authorized {
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }, completionHandler: { success, error in
                        if success {
                            print("Photo saved successfully")
                        } else {
                            print("Error saving photo: \(error != nil ? error! .localizedDescription : "")")
                        }
                    })
                }
            }
        }
    }
}

// 创建视图模型类来管理状态和处理更新逻辑（和之前一样，此处代码未修改相关逻辑，仅聚焦添加相机预览功能）
class ColorSettingsViewModel: ObservableObject {
    @Published var backgroundColor = Color.pink
    @Published var brightness: Double = 0.0
    @Published var saturation: Double = 1.0
}

// 自定义拍照按钮视图
struct CameraButton: View {
    var action: () -> Void
    var body: some View {
        Button(action: action) {
            ZStack {
                RoundedRectangle(cornerRadius: 15)
                  .fill(LinearGradient(gradient: Gradient(colors: [.black,.gray]), startPoint:.topLeading, endPoint:.bottomTrailing))
                  .frame(width: 50, height: 50)
                  .opacity(0.8)
                Image(systemName: "camera") // 使用系统相机图标，让人直观知道是拍照按钮
                  .resizable()
                  .aspectRatio(contentMode:.fit)
                  .frame(width: 30, height: 30)
                  .foregroundColor(.white)
            }
          .buttonStyle(PlainButtonStyle())
        }
    }
}

struct GlassButton: View {
    var action: () -> Void
    var body: some View {
        Button(action: action) {
            ZStack {
                RoundedRectangle(cornerRadius: 15)
                   .fill(LinearGradient(gradient: Gradient(colors: [.blue,.purple,.red]), startPoint:.topLeading, endPoint:.bottomTrailing))
                   .frame(width: 50, height: 50)
                   .opacity(0.8)
                Circle()
                   .fill(Color.white)
                   .frame(width: 30, height: 30)
                   .opacity(0.8)
            }
           .buttonStyle(PlainButtonStyle())
        }
    }
}

struct CameraPreview: UIViewRepresentable {
    var cameraManager = PhotoCaptureManager()  // 使用相机管理类实例
    
    func makeUIView(context: Context) -> UIView {
        let previewView = UIView()
        previewView.frame = UIScreen.main.bounds // 设置视图大小为屏幕大小，可根据实际父视图情况调整
        
        cameraManager.setupCamera()
        cameraManager.startCamera()
        
        if let previewLayer = cameraManager.previewLayer {
            previewLayer.frame = previewView.bounds
            previewView.layer.addSublayer(previewLayer)
        }
        
        // 计算圆形的尺寸和位置使其满足要求
        let circleDiameter = min(previewView.bounds.width, previewView.bounds.height) * 0.8 // 这里将直径设置为宽高较小值的60%，使半径变小，可按需调整比例
        let x = (previewView.bounds.width - circleDiameter) / 2
        let y = (previewView.bounds.height - circleDiameter) / 2 - circleDiameter * 0.3 // 往上移一些，这里往上移动了直径的20%，可按需调整比例
        let circleRect = CGRect(x: x, y: y, width: circleDiameter, height: circleDiameter)
        
        // 创建一个圆形的CAShapeLayer作为遮罩，只显示圆形区域的相机画面
        let circleMask = CAShapeLayer()
        let circlePath = UIBezierPath(ovalIn: circleRect)
        circleMask.path = circlePath.cgPath
        cameraManager.previewLayer?.mask = circleMask
        
        // 给圆形添加边框样式，使其更美观
        let borderLayer = CAShapeLayer()
        borderLayer.path = circlePath.cgPath
        borderLayer.strokeColor = UIColor.white.cgColor // 边框颜色，可自定义
        borderLayer.lineWidth = 5.0 // 边框宽度，可调整
        borderLayer.fillColor = UIColor.clear.cgColor
        previewView.layer.addSublayer(borderLayer)
        
        return previewView
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        // 如果视图有更新需求，可在这里添加相应逻辑，目前示例中暂无需额外更新操作
    }
}

struct ContentView: View {
    @StateObject var viewModel = ColorSettingsViewModel()
    @State private var isAnimating = false
    @State private var isUIHidden = false
    @State private var isTakingPhoto = false // 标记是否正在拍照
    @State var cameraPreview: CameraPreview = CameraPreview()
    
    var body: some View {
        ZStack {
            viewModel.backgroundColor
            .brightness(viewModel.brightness)
            .saturation(viewModel.saturation)
            .edgesIgnoringSafeArea(.all)
            cameraPreview
            .edgesIgnoringSafeArea(.all)
            VStack {
                if !isUIHidden {
                    ColorPicker("选择背景光", selection: $viewModel.backgroundColor)
                    .padding()
                    .font(.system(size: 18, weight:.bold)) // 使用系统字体，大小为18，粗细为粗体
                    .foregroundColor(.black)
                   .padding() // 增加内边距
                    
                    HStack {
                        Text("亮度")
                           .foregroundColor(.orange) // 设置字体颜色为紫色
                           .scaleEffect(isAnimating ? 1.4 : 1.0)
                           .padding()
                           .background(Color.black)
                           .cornerRadius(10)
                           .foregroundColor(.white)
                           .animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true), value: isAnimating) // 使用 animation(_:value:) 修饰符
                           .onAppear {
                                self.isAnimating = true // 当视图出现时启动动画
                            }
                        Slider(value: $viewModel.brightness, in: 0...1, step: 0.01)
                    }
                   .padding()
                    
                    HStack {
                        Text("饱和度")
                           .foregroundColor(.orange) // 设置字体颜色为紫色
                           .scaleEffect(isAnimating ? 1.4 : 1.0)
                           .padding()
                           .background(Color.black)
                           .cornerRadius(10)
                           .foregroundColor(.white)
                           .animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: true), value: isAnimating) // 使用 animation(_:value:) 修饰符
                           .onAppear {
                                self.isAnimating = true // 当视图出现时启动动画
                            }
                        Slider(value: $viewModel.saturation, in: 0...1, step: 0.01)
                    }
                   .padding()
                }
            }
            HStack {
                Spacer()
                VStack {
                    Spacer()
                    HStack {
                        GlassButton(action: {
                            isUIHidden.toggle()
                            self.isAnimating = false
                        })
                        Spacer()
                        CameraButton(action: {
                            self.isTakingPhoto = true
                            takePhoto(cameraPreview)
                        })
                    }
                }
            }
        }
      .onChange(of: isTakingPhoto) { newValue in
            if newValue {
//                takePhoto(cameraPreview)
                isTakingPhoto = false
            }
        }
    }
    
    func takePhoto(_ cameraPreview: CameraPreview) {
            cameraPreview.cameraManager.takePhoto()
            print("拍照完毕了")
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

